package com.zfei.gfb.controller;

import cn.hutool.core.date.DateUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.JsonObject;
import com.zfei.gfb.api.StatsService;
import com.zfei.gfb.api.domain.StatsTag;
import com.zfei.gfb.bean.Const;
import com.zfei.gfb.bean.Status;
import com.zfei.gfb.bean.StatusException;
import com.zfei.gfb.core.Auth;
import com.zfei.gfb.core.HttpJson;
import com.zfei.gfb.core.LogResult;
import com.zfei.gfb.dao.GfbJobMapper;
import com.zfei.gfb.device.AppContext;
import com.zfei.gfb.model.GfbJob;
import com.zfei.gfb.model.GfbUser;
import com.zfei.gfb.query.GfbJobQuery;
import com.zfei.gfb.request.GfbDelRequest;
import com.zfei.gfb.request.GfbGetRequest;
import com.zfei.gfb.request.GfbJobAddRequest;
import com.zfei.gfb.request.GfbJobEditRequest;
import com.zfei.gfb.util.Beans;
import com.zfei.gfb.util.Gsons;
import com.zfei.gfb.util.Now;
import com.zfei.gfb.vo.GfbJobListVo;
import com.zfei.gfb.vo.GfbJobVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * @author
 * @version 1.0
 */
@Auth(type = {Const.VILLAGE_MANAGER, Const.TOWN_MANAGER})
@Api(tags = "岗位信息管理接口")
@RestController
@RequestMapping("/web/job")
public class GfbJobController {

    @Resource
    private GfbJobMapper gfbJobMapper;

    @Resource
    private HttpSession httpSession;

    @Resource
    private StatsService statsService;

    @ApiOperation(value = "列表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = GfbJobListVo.class),
    })
    @LogResult
    @HttpJson("/list")
    public Object list(@RequestBody GfbJobQuery query) {
        query.check().build(Now::millis);
        GfbJobListVo result = new GfbJobListVo();

        int total = gfbJobMapper.total(query);
        result.setTotal(total);
        if (total == 0) {
            result.setData(Lists.newArrayList());
            return result;
        }

        List<GfbJob> records = gfbJobMapper.list(query);
        List<GfbJobVo> vos = Beans.copys(records, GfbJobVo.class);
        vos.forEach(vo ->
        {
            String ext = vo.getExt();
            String from;
            if (StringUtils.isBlank(ext)) {
                from = "client";
            } else {
                H5JobWantedController.JobExt jobExt = Gsons.fromJson(ext, H5JobWantedController.JobExt.class);
                if (jobExt.getFrom() != null) {
                    from = jobExt.getFrom();
                    vo.setSettleMethod(jobExt.getSettleMethod());
                } else {
                    from = "client";
                }
            }
            vo.setFrom(from);
            vo.setBrowseNum(statsService.get(vo.getId().toString(), StatsTag.JOB_BROWSE_COUNT).getNum());
        });
        result.setData(vos);
        return result;

    }

    @ApiOperation(value = "新增")
    @LogResult
    @HttpJson("/add")
    public Object add(@RequestBody GfbJobAddRequest request) {

        request.checkInsertNull();
        GfbUser user = (GfbUser) httpSession.getAttribute(AppContext.SESSION_WEB_USER);

        GfbJob record = Beans.copy(request, GfbJob.class);
        if (user.getId() != null) {
            record.setUserId(user.getId());
        }
//        record.setType(Const.JOB_GOV);
        record.setCreateTime(Now.millis());
        record.setUpdateTime(Now.millis());
        record.setCntime(DateUtil.now());
        record.setPubTime(Now.millis());
        record.setStatus(Const.STATUS_ON);
        Map<String, String> ext = Maps.newHashMap();
        ext.put("from", "admin");
        ext.put("settleMethod", request.getSettleMethod());
        record.setExt(Gsons.toJson(ext));

        gfbJobMapper.insertSelective(record);
        return null;
    }

    @ApiOperation(value = "编辑")
    @LogResult
    @HttpJson("/edit")
    public Object edit(@RequestBody GfbJobEditRequest request) {

        request.checkUpdateNull();

        GfbJob record = gfbJobMapper.selectByPrimaryKey(request.getId());
        if (record == null) {
            throw new StatusException(Status.NOT_EXIST);
        }

        BeanUtils.copyProperties(request, record);
        record.setUpdateTime(Now.millis());

        Map<String, String> ext = Maps.newHashMap();
        ext.put("from", "admin");
        ext.put("settleMethod", request.getSettleMethod());
        record.setExt(Gsons.toJson(ext));
        gfbJobMapper.updateByPrimaryKeySelective(record);

        return null;
    }

    @ApiOperation(value = "删除")
    @LogResult
    @HttpJson("/del")
    public Object del(@RequestBody GfbDelRequest request) {
        Integer id = request.getId();

        if (id == null) {
            throw new StatusException(Status.INVALID_ARGUMENT);
        }

        GfbJob record = gfbJobMapper.selectByPrimaryKey(id);
        if (record == null) {
            throw new StatusException(Status.NOT_EXIST);
        }

        gfbJobMapper.deleteByPrimaryKey(id);
        return null;
    }

    @ApiOperation(value = "详情")
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = GfbJobVo.class),
    })
    @LogResult
    @HttpJson("/get")
    public Object get(@RequestBody GfbGetRequest request) {
        request.checkGetNull();
        Integer id = request.getId();

        GfbJob record = gfbJobMapper.selectByPrimaryKey(id);
        GfbJobVo vo = Beans.copy(record, GfbJobVo.class);

        String ext = record.getExt();
        String from;
        if (StringUtils.isBlank(ext)) {
            from = record.getType() == Const.JOB_GOV ? "admin" : "client";
        } else {
            JsonObject jsonObject = Gsons.parseJsonObject(ext);
            if (jsonObject.has("from")) {
                from = jsonObject.get("from").getAsString();
                vo.setSettleMethod(jsonObject.get("settleMethod").getAsString());
            } else {
                from = record.getType() == Const.JOB_GOV ? "admin" : "client";
            }
        }

        vo.setFrom(from);

        return vo;
    }
}
